package cz.bernhard.playground.persistance.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public abstract class BaseHibernateDao<T, ID> implements BaseDao<T, ID> {
	
	private SessionFactory sessionFactory;
	
	public BaseHibernateDao() {

		Configuration configuration = new Configuration();
		sessionFactory = configuration.configure().buildSessionFactory();
	
	}
	
	protected Session getSession() {
		return sessionFactory.openSession();
	}
	
	public List<T> findAll() {
		return getSession().createQuery("from " + getEntityClass().getSimpleName()).list();
	}

	public T findById(ID id) {
		return (T) getSession().get(getEntityClass(), (Serializable) id);
	}

	public T deleteById(ID id) {
		// TODO Auto-generated method stub
		return null;
	}

	public ID save(T entityToSave) {
		Session session = getSession();
		ID entity = (ID) session.save(entityToSave);
		session.close();
		
		return entity;
	}

	/**
	 * Must be here hence I need class type for find methods and it's not possible to interfere this information
	 * from generics (because java uses type-erasure style of generics due compatibility with old versions of java)
	 * 
	 * @return class type of entity which is this dao for
	 */
	protected abstract Class<T> getEntityClass();

}
